package com.newlink.building.userinfo.mvp

import android.content.Context
import android.util.Log
import com.newlink.building.common_base.base.BasePresenter
import com.newlink.building.common_base.ext.ss
import com.newlink.building.common_base.utils.logDebug
import com.newlink.building.userinfo.mvp.contract.Module_UserInfo_AboutContract
import com.newlink.building.userinfo.mvp.model.Module_UserInfo_AboutModel

/**
 * @author wangyang
 * @date 2022/9/20
 * @description 我的-关于页面的Presenter
 */
class Module_UserInfo_AboutPresenter : BasePresenter<Module_UserInfo_AboutContract.Model, Module_UserInfo_AboutContract.View>(),
    Module_UserInfo_AboutContract.Presenter {


    override fun attachView(v: Module_UserInfo_AboutContract.View) {
        super.attachView(v)
        Log.e("fvl_dbg", "--------v is not null-------")
        if (mView == null) {
            Log.e("fvl_dbg", "--------mView is null-------")
        }
    }

    override fun createModel(): Module_UserInfo_AboutContract.Model = Module_UserInfo_AboutModel()

    override fun getData(context: Context, token: String) {

        Log.e("fvl_dbg", "--------Hello Dog...-------" + checkViewAttached())
        logDebug<Module_UserInfo_AboutPresenter>("---->  getData  判断新版本")
        if (mModel == null) {
            mModel = Module_UserInfo_AboutModel()
        }
        mModel?.let { model ->
            logDebug<Module_UserInfo_AboutPresenter>("---->  00")
            model.getData(token).ss(model, mView) { dataStr ->

                logDebug<Module_UserInfo_AboutPresenter>("11---->  $dataStr")

                dataStr?.let {
                    val versionBean = it.data
                    val remoteVersion = versionBean.versionCode.toInt()
                    val currentVersion = getCurrentAppVersionCode(context)

                    if (remoteVersion > currentVersion) {
                        mView?.hasNewVersion(versionBean)
                    } else {
                        mView?.noNewVersion()
                    }
                }

            }
        }
    }

    override fun getCurrentAppVersion(context: Context): String {
        var versionName = ""
        try {
            val pm = context.packageManager
            val pi = pm.getPackageInfo(context.packageName, 0)
            versionName = pi.versionName
            if (versionName.isNullOrEmpty()) {
                return versionName
            }
        } catch (e: java.lang.Exception) {
            Log.e("VersionInfo", "Exception", e)
        }
        return versionName
    }

    fun getCurrentAppVersionCode(context: Context): Int {
        var versionName = 0
        try {
            val pm = context.packageManager
            val pi = pm.getPackageInfo(context.packageName, 0)
            versionName = pi.versionCode

        } catch (e: java.lang.Exception) {
            Log.e("VersionInfo", "Exception", e)
        }
        return versionName
    }
}